package com.insigma.business.common.utils;

import cn.hutool.core.util.ClassUtil;
import com.insigma.business.gateway.api.ServiceInvoker;
import com.insigma.business.gateway.dto.MethodClassDTO;
import com.insigma.business.qrcode.common.annotation.ApiServiceType;
import com.insigma.business.qrcode.common.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: huangjh
 * @description:
 * @date: 2024-04-12 10:09
 */
@Slf4j
@Component
public class AnnotationUtils {

    public static AnnotationUtils annotationUtils; //声明对象


    @Autowired
    private ServiceInvoker serviceInvoker;

    private static ServiceInvoker serviceInvokerUtils;

    public static Map<String, MethodClassDTO> classBeanNameMap = new HashMap<>();

    @PostConstruct
    public void init() {
        annotationUtils=this;
        serviceInvokerUtils = this.serviceInvoker;
    }

    public static Map<Method, MethodClassDTO> handlePackageClassMap(String packageName){
        Set<Class<?>> classes = ClassUtil.scanPackage(packageName);
        LogUtil.info(log, "已获取到:" + classes.size());
        Map<Method, MethodClassDTO> resMap = new ConcurrentHashMap<>();
        for (Class<?> aClass : classes) {
            if (null==aClass){
                continue;
            }
            Method[] methodList = null;
            try {
                methodList= aClass.getMethods();
            }catch (Exception e){
                continue;
            }
            for (Method method : methodList) {
                if (method.getAnnotation(ApiServiceType.class) != null) {
                    String name = method.getAnnotation(ApiServiceType.class).name();
                    String menu = method.getAnnotation(ApiServiceType.class).menu();
                    String classBeanName = aClass.getSimpleName().substring(0, 1).toLowerCase() + aClass.getSimpleName().substring(1);
                    MethodClassDTO build = MethodClassDTO.builder().classBeanName(classBeanName).name(name).menu(menu).build();
                    resMap.put(method, build);
                    //放入gw对应的描述
                    if (StringUtils.isNotBlank(method.getAnnotation(ApiServiceType.class).value())){
                        ApiServiceType annotation = method.getAnnotation(ApiServiceType.class);
                        annotationUtils.classBeanNameMap.put(annotation.value(),MethodClassDTO.builder()
                                        .value(annotation.value())
                                .classBeanName(classBeanName).name(name).menu(menu).build());
                    }
                }
            }}
        return resMap;
    }
}
